package com.feeyo.groundservice.wifi

import android.view.Gravity
import com.feeyo.android.http.NetClient
import com.feeyo.android.util.switch
import com.feeyo.groundservice.wifi.api.IApi
import com.feeyo.groundservice.wifi.util.BaseObserver
import com.feeyo.groundservice.wifi.util.InitLightBoxIP
import com.feeyo.groundservice.wifi.util.LightBoxCache
import com.feeyo.groundservice.wifi.util.PlayTipsEvent
import com.feeyo.groundservice.wifi.util.post
import com.feeyo.groundservice.wifi.util.toast
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit

/**
 *作者：QLH on 2020-11-01
 *描述：http方式发送数据到灯箱
 */
object LightBoxHttp {

    /**初始化灯箱,获取IP,缓存下来**/
    fun initLightBoxIp() = InitLightBoxIP.initLightBoxIp()

    /**欢迎语**/
    fun welcome() {
        getApi()?.apply {
            welcome().switch()
                .subscribe(object : BaseObserver<Any>() {
                    override fun onSuccess(t: Any?) {

                    }
                })
        } ?: toast("灯箱IP获取失败", Gravity.CENTER)
    }

    /**发送 航班和机位，如果需要上屏成功语音提示，监听data class PlayTipsEvent(val tips:String)
     * @param
     * {
    ‘flight’:
    ‘CA1234’,
    ‘apron’: ‘305A’
    }
     * **/
    fun flight(flight: String, apron: String) {

        getApi()?.apply {
            flight(flight, apron.ifEmpty { "000" }).enqueue(object :Callback<Any>{
                override fun onResponse(call: Call<Any>, response: Response<Any>) {
                    if (response.isSuccessful){
                        toast("上屏成功")
                        PlayTipsEvent("$flight 上屏成功").post()
                    }
                }

                override fun onFailure(call: Call<Any>, t: Throwable) {

                }
            })

        } ?: toast("灯箱IP获取失败", Gravity.CENTER)
    }


    /**发送 滚动信息**/
    fun scrollMessage(msg: String) {

        getApi()?.apply {
            scrollMessage(msg, speed = 1)
                .switch()
                .subscribe(object : BaseObserver<Any>() {
                    override fun onSuccess(t: Any?) {

                    }
                })
        } ?: toast("灯箱IP获取失败", Gravity.CENTER)

    }

    private fun getApi(): IApi? = LightBoxCache.getLightBoxIP()?.let {
        NetClient.getRetrofit(it).create(IApi::class.java)
    }
}